/** 
 * @Title:工具类  
 * @Desription:生成Sql语句帮助类
 * @Company:MDKG
 * @ClassName:SqlHelper.java
 * @Author:Wangjz
 * @CreateDate:2013-11-26   
 * @UpdateUser:Wangjz  
 * @Version:0.1 
 *    
 */ 

package com.midian.common.dao;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;

/** 
 * @ClassName: SqlHelper 
 * @Description: 生成Sql语句帮助类 
 * @author: Wangjz
 * @date: 2013-11-26
 * 
 */
public class SqlHelper implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = -1973557061114007079L;

	/**
	 * 创建List的IN查询条件
	 * @param propertyName 属性名称
	 * @param conditonList 条件集合
	 * @param sb sql语句
	 */
	public static void createConditionOfTypeIn(String propertyName, List conditonList, StringBuilder sb) {
		createConditionOfTypeIn(propertyName, conditonList, sb, "and");
	}
	
	/**
	 * 创建List的IN查询条件
	 * @param propertyName 属性名称
	 * @param conditonList 条件集合
	 * @param sb sql语句
	 * @param logicDesc 逻辑关键字
	 */
	public static void createConditionOfTypeIn(String propertyName, List conditonList, StringBuilder sb, String logicDesc) {
		int size = 0;
		
		if(StringUtils.isBlank(propertyName) || sb == null 
				|| conditonList == null || conditonList.isEmpty()) {
			return;
		}
		//拼接逻辑运算符(and或者or等等)
		if(StringUtils.isNotBlank(logicDesc)) {
			sb.append(" ").append(logicDesc).append(" ");
		}
		sb.append(propertyName).append(" in (");
		size = conditonList.size() - 1;
		for (int i = 0; i <= size; i++) {
			if (i != size) {
				sb.append(" ?,");
			} else {
				sb.append(" ? ");
			}
		}
		sb.append(")");
	}
	
	/**
	 * 处理排序的语句
	 * @param orderHelperList 排序对象列表
	 * @return
	 */
	public static String opOrder(StringBuilder sb, List<OrderHelper> orderHelperList) {
		if (sb != null && orderHelperList != null && orderHelperList.size() != 0) {
			sb.append(" order by ");
			for (OrderHelper orderHelper : orderHelperList) {
				if(OrderHelper.Type.ASC == orderHelper.getType()) {
					sb.append(orderHelper.getPropertyName()).append(" asc ,");
				} else {
					sb.append(orderHelper.getPropertyName()).append(" desc ,");
				}
			}
			sb.delete(sb.length() - 1, sb.length());
		}
		return sb.toString();
	}
	
	/**
	 * 将Map集合转换为VO集合
	 * @param mapList Map集合
	 * @param clazz 目标类型
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> List<T> convertMapListToVoList(List<Map<String, Object>> mapList, Class<T> clazz) {
		List<T> voList = new ArrayList<T>();
		try {
			if(mapList != null && !mapList.isEmpty()) {
				for (Map<String, Object> map : mapList) {
					Object rootObj = clazz.newInstance(); //获取根对象
					voList.add((T) rootObj); //添加根对象到列表中
					for(Entry<String, Object> entry : map.entrySet()) {
						String propNameChain = entry.getKey(); //获取属性链
						String[] propNames = propNameChain.split("\\."); //拆分属性链
						Object lastObj = rootObj; //将上一对象默认保存为根对象（同一个map使用同一个根对象）
						for(int i = 0; i < propNames.length; i++) {
							String propName = propNames[i]; //获取属性
							String getMethodName = "get" + propName.substring(0, 1).toUpperCase() + propName.substring(1); //获取属性的get方法名称
							Method getMethod = lastObj.getClass().getMethod(getMethodName); //获取属性的get方法对象
							Class<?> paramType = lastObj.getClass().getMethod(getMethodName).getReturnType(); //获取get方法的返回值
							String setMethodName = "set" + propName.substring(0, 1).toUpperCase() + propName.substring(1); //获取set方法名称
							Method setMethod = lastObj.getClass().getMethod(setMethodName, paramType); //获取set方法对象
							
							Object paramVal = null; //参数值
							//如果已到达属性链尾部（即链中的最后一个属性），直接从map中获取属性的值
							if(i == propNames.length - 1) {
								paramVal = entry.getValue();
							} else {
							//如果没到达属性链尾部，先通过get方法尝试获取该对象
								paramVal = getMethod.invoke(lastObj);
								//如果通过get方法获取对象为空，新建一个对象，并通过set方法将对象设置到前一对象中
								if(paramVal == null) {
									paramVal = paramType.newInstance();
								}
							}
							setMethod.invoke(lastObj, paramVal);
							lastObj = paramVal;
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return voList;
	}
	
	/**
	 * 首或尾id过滤
	 * @param firstId 首id
	 * @param lastId 尾id
	 * @param alias 查询语句别名
	 * @param sb StringBuilder对象
	 * @param conditionMap 条件集对象
	 */
	public static void createFilterIdCondition(Integer firstId, Integer lastId, String alias, StringBuilder sb, List<Object> valueList) {
		String idFilterType = ""; //id过滤规则
		Integer targetId = null; //目标id
		if(firstId != null) {
			//获取首id，置空尾id和fetchSize
			targetId = firstId;
			idFilterType = "first";
		} else if(lastId != null) {
			//获取尾id
			targetId = lastId;
			idFilterType = "last";
		}
		//id过滤
		if(targetId != null && StringUtils.isNotBlank(idFilterType)) {
			sb.append(" and ");
			if(StringUtils.isNotBlank(alias)) {
				sb.append(alias).append(".");
			}
			sb.append("id");
			if("first".equals(idFilterType)) {
				sb.append(">"); //首id，大于
			} else if("last".equals(idFilterType)) {
				sb.append("<"); //尾id，小于
			}
			sb.append("?");
			valueList.add(targetId);
		}
	}
}
